package com.njlime.core.sdk.wechat;

import com.alibaba.fastjson.JSON;
import com.njlime.core.base.controller.BaseAppController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.sdk.wechat.jsapi.AccessToken;
import com.njlime.core.sdk.wechat.jsapi.JsapiTicket;
import com.njlime.core.sdk.wechat.jsapi.JssdkSign;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.AppWxInterceptor;
import com.njlime.sys.entities.UnitWxConfig;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 微信控制器
 * Created by Dean on 2017-9-20.
 */
@Controller
@RequestMapping(value = "app/wechat")
public class WechatController extends BaseAppController{

    @ResponseBody
    @RequestMapping(value = "getWechatData",method = POST)
    public String getWechatData(HttpServletRequest request, String url){
        try {
            Integer rootUnitId = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_ROOT_UNIT_ID);
            Integer unit_id = (Integer) request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
            if(rootUnitId != null) {
                UnitWxConfig unitWxConfig = unitService.getWxConfig(rootUnitId);
                if(unitWxConfig != null && !StringUtil.isEmpty(unitWxConfig.getApp_id())){
                    AccessToken accessToken = WeChatUtil.getAccessToken(unitWxConfig.getApp_id(), unitWxConfig.getApp_secret());
                    JsapiTicket jsapiTicket = WeChatUtil.getJsApiTicket(accessToken.getToken(),unitWxConfig.getApp_id());
                    Map<String,String> map = JssdkSign.sign(jsapiTicket.getTicket(),url, unitWxConfig.getApp_id());
                    map.put("unit_id", unit_id + "");
                    return JSON.toJSONString(map);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "获取微信信息出错");
        }
        return toJsonErrorData(ExceptionState.PERMISSION_EXCEPTION,"未绑定微信");
    }

    @RequestMapping(value = "getWxCode")
    public void getWxCode(HttpServletRequest request, HttpServletResponse response, String appid){
        try {
            UnitWxConfig wxConfig = unitService.getWxConfigByAppid(appid);
            logger.info("获取微信Code：" + appid);
            if(wxConfig != null && !StringUtil.isEmpty(wxConfig.getApp_id())){
                String baseUrl = "";
                if (request.getServerPort() == 80 || request.getServerPort() == 443) {
                    baseUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
                } else {
                    baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                }
                String backUri = new String(Base64.encodeBase64(request.getParameter("backUri").getBytes("UTF-8")), "UTF-8");
                String redirect_uri = baseUrl + "/app/wechat/dealWxCode?backUri=" + backUri;
                response.sendRedirect(UrlHeader.AUTH_URL.replace("APPID", wxConfig.getApp_id()).replace("REDIRECT", redirect_uri)
                        .replace("STATE", request.getParameter("state")));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "dealWxCode")
    public void getWxCode(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取微信授权
            String code = request.getParameter("code");
            logger.debug("微信Code：" + code);
            String backUri = new String(Base64.decodeBase64(request.getParameter("backUri").getBytes("UTF-8")), "UTF-8");
            if(backUri.contains("?")){
                backUri += "&code=" + code + "&state=" + request.getParameter("state");
            }else{
                backUri += "?code=" + code + "&state=" + request.getParameter("state");
            }
            response.sendRedirect(backUri);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "getWxToken",method = POST)
    public String getWxToken(HttpServletRequest request, String appid){
        UnitWxConfig wxConfig = unitService.getWxConfigByAppid(appid);
        if(wxConfig != null && !StringUtil.isEmpty(wxConfig.getApp_id())) {
            AccessToken accessToken = WeChatUtil.getAccessToken(wxConfig.getApp_id(), wxConfig.getApp_secret());
            return toJsonSuccessData(accessToken);
        }
        return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "获取token失败");
    }

    @ResponseBody
    @RequestMapping(value = "getWxJsToken",method = POST)
    public String getWxJsToken(HttpServletRequest request, String appid){
        UnitWxConfig wxConfig = unitService.getWxConfigByAppid(appid);
        if(wxConfig != null && !StringUtil.isEmpty(wxConfig.getApp_id())) {
            AccessToken accessToken = WeChatUtil.getAccessToken(wxConfig.getApp_id(), wxConfig.getApp_secret());
            JsapiTicket jsapiTicket = WeChatUtil.getJsApiTicket(accessToken.getToken(), wxConfig.getApp_secret());
            return toJsonSuccessData(jsapiTicket);
        }
        return toJsonErrorData(ExceptionState.UNKNOWN_EXCEPTION, "获取jsapi失败");
    }

}
